package com.zw.yzk.kabu.presenter;

import android.support.v7.app.AppCompatActivity;

import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.base.BaseSubscriber;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.network.entity.Entity;
import com.zw.yzk.kabu.data.network.task.CancelOrderTask;
import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.domain.repository.UseCase;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.model.PublishImageModel;
import com.zw.yzk.kabu.view.view.RefundView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.inject.Inject;
import javax.inject.Named;

/**
 * Created by zhanwei on 2017/3/18.
 */

public class RefundPresenter implements Presenter {

    private UseCase refund;
    private UseCase getUploadToken;
    private AppCompatActivity activity;
    private RefundView refundView;
    private UploadManager uploadManager;
    private int imageCount;
    private CancelOrderTask task;
    private boolean cancel;
    private String uploadToken;

    @Inject
    public RefundPresenter(@Named("cancelUseCase") UseCase refund,
                           @Named("uploadImageTokenUseCase") UseCase getUploadToken,
                           AppCompatActivity activity) {
        this.refund = refund;
        this.getUploadToken = getUploadToken;
        this.activity = activity;
    }

    public void setView(RefundView view) {
        this.refundView = view;
    }

    public void getUploadImageToken() {
        getUploadToken.execute(new GetUploadTokenSubscriber(activity), new Task());
    }

    public void refund(String orderId, String reason, List<PublishImageModel> list) {

        if (list == null || list.isEmpty()) {
            refund.execute(new RefundSubscriber(activity), new CancelOrderTask(orderId, reason, null));
        } else {
            imageCount = list.size();
            List<String> tmp = new ArrayList<>();
            task = new CancelOrderTask(orderId, reason, tmp);

            uploadToQiNiu(list, uploadToken);
        }
    }

    private void uploadToQiNiu(List<PublishImageModel> data, String token) {
        if (uploadManager == null) {
            uploadManager = new UploadManager(
                    new Configuration.Builder()
                            .build());
        }
        for (int i = 0; i < data.size(); i++) {
            String expectKey = UUID.randomUUID().toString();
            uploadManager.put(data.get(i).getContentPath(), expectKey, token, new UpCompletionHandler() {
                public void complete(String k, ResponseInfo info, JSONObject response) {
                    if (info.isOK()) {
                        getImageUrl(response);
                    } else {
                        cancel = true;
                        LoadingDialogManager.getInstance().dismissLoadingDialog();
                        ToastManager.getInstance().showToast(activity, activity.getResources().getString(R.string.upload_image_failed));
                    }
                }
            }, null);
        }
    }

    private synchronized void getImageUrl(JSONObject response) {
        String url = response.optString("key");
        task.imageList.add(ActivityConstant.QINIU_PERFIX + url);
        if (imageCount == task.imageList.size() && !cancel) {
            //图片已经全部上传完成，将结果组装完成上传到服务器
            refund.execute(new RefundSubscriber(activity), task);
        }
    }

    @Override
    public void resume() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        refund.unSubscribe();
        getUploadToken.unSubscribe();
    }

    public class RefundSubscriber extends BaseSubscriber<Entity> {

        public RefundSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onNext(Entity entity) {
            super.onNext(entity);
            ToastManager.getInstance().showToast(activity, activity.getResources().getString(R.string.refund_success));
            refundView.refundSuccess();
        }

        @Override
        public void onCompleted() {
            super.onCompleted();
            LoadingDialogManager.getInstance().dismissLoadingDialog();
        }

        @Override
        public String addErrorMessage() {
            return activity.getResources().getString(R.string.refund_failed);
        }
    }

    private class GetUploadTokenSubscriber extends BaseSubscriber<String> {

        public GetUploadTokenSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onNext(String s) {
            super.onNext(s);
            uploadToken = s;
        }

        @Override
        public String addErrorMessage() {
            return activity.getResources().getString(R.string.get_upload_image_token_failed);
        }
    }
}
